package android.slc.app.startup.task;

import android.slc.app.shutdown.ShutdownManager;
import android.slc.app.startup.TaskConstant;
import android.slc.appbase.api.slc.SlcApi;
import android.slc.appbase.repository.local.sp.AppConfig;
import android.slc.appbase.config.ConstantsBase;
import android.slc.appbase.utils.AppPathUtils;
import android.slc.appbase.utils.SlcCrashUtils;
import android.slc.box.anchors.task.Task;
import android.slc.box.core.utils.ConsoleManager;
import android.slc.box.core.utils.ShortCutUtils;
import android.slc.module.component.image_loader.ImageLoaderConfig;
import android.slc.module.component.mock.MockManager;
import android.slc.module.project.repository.local.ProjectConfig;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import org.jetbrains.annotations.NotNull;

import java.io.File;

public class TaskSlc extends Task {

    public TaskSlc() {
        super(TaskConstant.TASK_SLC, false);
    }

    @Override
    protected void run(@NotNull String s) {
        if (AppConfig.isIsRelease()) {
            new ConsoleManager().initialize();
        }
        //app的启动exe文件位置
        File appFile = FileUtil.file(FileUtil.getParent(AppPathUtils.getRootDir(), 1), AppConfig.getAppExeName());
        SlcCrashUtils.init(new SlcCrashUtils.OnCrashListener() {
            @Override
            public void onCrash(String crashInfo, Throwable e, SlcCrashUtils.OnNotifyUncaughtExceptionListener onNotifyUncaughtExceptionListener) {
                onNotifyUncaughtExceptionListener.onNotifyUncaughtException(e);
                if (e instanceof OutOfMemoryError && ProjectConfig.getInstance().isAutoRestart()) {
                    ShutdownManager.shutdown();
                    try {
                        if (appFile.exists()) {
                            RuntimeUtil.execForStr(StrUtil.format("\"{}\"", appFile.getAbsolutePath()));
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    } finally {
                        System.exit(0);
                    }
                }
            }
        });
        //创建快捷方式
        if (appFile.exists()) {
            try {
                if (AppConfig.isIsRelease()) {
                    ShortCutUtils.INSTANCE.createAppStartup(appFile, false);
                }
                ShortCutUtils.INSTANCE.createDesktopShortCut(appFile, AppConfig.getAppName(), false);
            } catch (Exception e) {

            }
        }
        //初始化api
        SlcApi.init();
        //初始化MockManager
        MockManager.getInstance().init(ProjectConfig.getInstance().isOpenMock(), ProjectConfig.getInstance().getMockPeriod());
        //imagerLoader初始化
        ConstantsBase.Value.REC_CACHE_PATH = AppPathUtils.createAppCacheFile("file").getAbsolutePath();
        ImageLoaderConfig.getInstance().setSavePath(ConstantsBase.Value.REC_CACHE_PATH);
    }
}
